<template>
  <div class="editor">
    <div id="vditor" class="vditor"></div>
  </div>
</template>

<script>
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import { reqOssUpload } from '@/api/oss';
import SparkMD5 from "spark-md5";

export default {
  name: 'blog-editor',
  data() {
    return {
      contentEditor: {},
    }
  },
  mounted() {
    this.contentEditor = new Vditor('vditor', {
      minHeight: 600,
      placeholder: '在此处写文章',
      theme: 'classic',
      counter: {
        enable: true,
        type: 'markdown'
      },
      preview: {
        delay: 0,
        hljs: {
          style: 'monokai',
          lineNumber: true
        }
      },
      tab: '\t',
      typewriterMode: true,
      toolbarConfig: {
        pin: true
      },
      counter: {
        enable: true,
        type: '字数统计',
      },
      cache: {
        enable: false
      },
      outline: {
        enable: true
      },
      mode: 'wysiwyg',
      toolbar: [
        'emoji',
        'headings',
        'bold',
        'italic',
        'strike',
        'link',
        '|',
        'list',
        'ordered-list',
        'check',
        'outdent',
        'indent',
        '|',
        'quote',
        'line',
        'code',
        'inline-code',
        'insert-before',
        'insert-after',
        '|',
        // "upload",
        {
          hotkey: "",
          name: "upload",
          // tipPosition: "s",
          tip: "上传图片",
          className: "right",
        },
        // 'record',
        'table',
        '|',
        'undo',
        'redo',
        '|',
        "outline",
        'edit-mode',
        {
          name: 'more',
          toolbar: [
            'content-theme',
            'code-theme',
            'export',
            'fullscreen',
            'both',
            'preview',
            'info',
            'help',
            "devtools",
          ],
        }],
      upload: {
        accept: 'image/jpg, image/jpeg, image/png',//规定上传的图片格式
        multiple: false,
        fieldName: 'file',
        max: 5 * 1024 * 1024,//上传图片的大小
        extraData: { 'access_token': this.token }, //为 FormData 添加额外的参数
        // linkToImgUrl: this.gb.reqPath('/v1/Activity/upload'),
        filename(name) {
          return name.replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
            .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
            .replace("/\\s/g", "");
        },
        validate(msg) {
          console.log(msg + "格式")
        },
        //粘贴图片回显处理，如果有图片加了防盗链，则让后台代理替换成自己的图片
        linkToImgFormat(files) {
          let code = 0
          let msg = ''
          let data = JSON.parse(files)
          // let linkImgName = data.result.path
          // //上传图片请求状态
          if (data.ret_code == 200) {
            // let lastTipNum = linkImgName.substr(linkImgName.lastIndexOf('/', linkImgName.lastIndexOf('/') - 1) + 1);
            // let index = lastTipNum.lastIndexOf("\/");
            // let imgUrl = decodeURI(lastTipNum.substring(index + 1, lastTipNum.length));
            let responseData = self.gb.imgOutLinkPath(data.result.path)
            let succUrl = {}
            let originalURL = 'originalURL'
            let url = 'url'
            succUrl[originalURL] = data.result.originalURL
            succUrl[url] = responseData
            let end = JSON.stringify({
              msg,
              code,
              data: succUrl
            })
            return end
          } else {
            self.$message({
              message: '图片上传失败！',
              type: 'error'
            })
          }
        },
        //上传图片回显处理
        format(files, responseText) {
          // let imageResult = JSON.parse(responseText)
          let code = JSON.parse(responseText)
          let msg = JSON.parse(responseText)
          let data = JSON.parse(responseText)
          let filName = data.result.cover_files
          //上传图片请求状态
          if (data.ret_code == 200) {
            let lastTipNum = filName.substr(filName.lastIndexOf('/', filName.lastIndexOf('/') - 1) + 1);
            let index = lastTipNum.lastIndexOf("\/");
            self.imgNameStr = decodeURI(lastTipNum.substring(index + 1, lastTipNum.length));
            let responseData = self.gb.imgPath(data.result.cover_files)
            let succ = {}
            succ[self.imgNameStr] = responseData
            //图片回显
            return JSON.stringify({
              msg,
              code,
              data: {
                errFiles: [],
                succMap: succ
                // succMap: {
                //   'default.png': `${responseData}`
                // }
              }
            })
          } else {
            self.$message({
              message: '图片上传失败！',
              type: 'error'
            })
          }

        },
        error(msg) {
          console.log(msg + "上传失败了")
        },
        handler: (files) => this.upload(files[0]),
      },
    })
  },
  methods: {
    upload(file) {
      this.calculateMD5(file);
    },
    calculateMD5(file) {
      const chunkSize = 1024 * 1024; // 1MB 分块
      const spark = new SparkMD5.ArrayBuffer(); // 使用spark-md5的ArrayBuffer方法
      const fileReader = new FileReader();
      let offset = 0;

      fileReader.onload = (e) => {
        // 每次读取一块文件数据后，更新MD5计算
        spark.append(e.target.result); // 追加数据到MD5计算器
        offset += chunkSize;

        if (offset < file.size) {
          // 如果文件还没有读取完，继续读取下一块
          this.readNextChunk(file, fileReader, offset, chunkSize);
        } else {
          // 文件读取完，输出最终的MD5值
          this.md5 = spark.end(); // 获取最终的MD5值
          const formData = new FormData()
          formData.append('file', file)
          formData.append('fileMd5', this.md5)
          formData.append('fileType', file.type)
          this.uploadToOss(formData)
        }
      };

      fileReader.onerror = (error) => {
        console.error('文件读取错误:', error);
      };

      // 开始读取文件的第一块数据
      this.readNextChunk(file, fileReader, offset, chunkSize);
    },
    readNextChunk(file, fileReader, offset, chunkSize) {
      // 读取文件的一个块
      const slice = file.slice(offset, offset + chunkSize); // 获取文件的一个分块
      fileReader.readAsArrayBuffer(slice); // 读取当前分块
    },
    uploadToOss(formData) {
      reqOssUpload(formData).then((res) => {
        this.imgUrl = res.data;
        this.contentEditor.insertValue(`![${formData.get('file').name}](${res.data})`);
        this.$message.success("上传成功");
      }).catch((error) => {
        this.$message.error(error);
      })
    },
  }

}
</script>

<style scoped>
::v-deep .vditor img {
  max-width: 100%;
  height: 400px;
}
</style>